<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="handleClose"
  >
    <div class="bulk-operation-dialog">
      <!-- 操作类型选择 -->
      <div v-if="!selectedOperation" class="operation-selection">
        <h3>{{ $t('BulkOperation.SelectOperation') }}</h3>
        <el-radio-group v-model="selectedOperationType" class="operation-types">
          <el-radio
            v-for="operation in availableOperations"
            :key="operation.type"
            :value="operation.type"
            class="operation-radio"
          >
            <div class="operation-item">
              <div class="operation-icon">
                <el-icon :size="24">
                  <component :is="operation.icon" />
                </el-icon>
              </div>
              <div class="operation-info">
                <div class="operation-name">{{ operation.name }}</div>
                <div class="operation-description">{{ operation.description }}</div>
                <div v-if="operation.requiresConfirmation" class="operation-warning">
                  <el-alert
                    :title="operation.warning"
                    type="warning"
                    :closable="false"
                    show-icon
                  />
                </div>
              </div>
            </div>
          </el-radio>
        </el-radio-group>
      </div>

      <!-- 操作配置 -->
      <div v-else class="operation-config">
        <div class="selected-operation-header">
          <h3>{{ selectedOperation.name }}</h3>
          <el-button type="text" @click="backToSelection">
            <el-icon><ArrowLeft /></el-icon>
            {{ $t('Common.Back') }}
          </el-button>
        </div>

        <div class="operation-preview">
          <el-alert
            :title="$t('BulkOperation.SelectedItemsCount', { count: selectedItems.length })"
            type="info"
            :closable="false"
            show-icon
          />
        </div>

        <!-- 动态配置表单 -->
        <el-form
          ref="formRef"
          :model="operationConfig"
          :rules="formRules"
          label-width="120px"
          class="operation-form"
        >
          <!-- 激活/停用操作 -->
          <template v-if="selectedOperationType === 'activate' || selectedOperationType === 'deactivate'">
            <el-form-item :label="$t('BulkOperation.EffectiveDate')">
              <el-date-picker
                v-model="operationConfig.effectiveDate"
                type="datetime"
                :placeholder="$t('BulkOperation.SelectEffectiveDate')"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item :label="$t('BulkOperation.Reason')">
              <el-input
                v-model="operationConfig.reason"
                type="textarea"
                :rows="3"
                :placeholder="$t('BulkOperation.ReasonPlaceholder')"
              />
            </el-form-item>
          </template>

          <!-- 删除操作 -->
          <template v-if="selectedOperationType === 'delete'">
            <el-form-item :label="$t('BulkOperation.ConfirmDelete')" required>
              <el-checkbox v-model="operationConfig.confirmDelete">
                {{ $t('BulkOperation.ConfirmDeleteText') }}
              </el-checkbox>
            </el-form-item>
            <el-form-item :label="$t('BulkOperation.DeleteReason')" required>
              <el-input
                v-model="operationConfig.deleteReason"
                type="textarea"
                :rows="3"
                :placeholder="$t('BulkOperation.DeleteReasonPlaceholder')"
              />
            </el-form-item>
            <el-form-item :label="$t('BulkOperation.ForceDelete')">
              <el-checkbox v-model="operationConfig.forceDelete">
                {{ $t('BulkOperation.ForceDeleteText') }}
              </el-checkbox>
              <div class="form-help">
                <el-alert
                  :title="$t('BulkOperation.ForceDeleteWarning')"
                  type="error"
                  :closable="false"
                  show-icon
                />
              </div>
            </el-form-item>
          </template>

          <!-- 角色分配操作 -->
          <template v-if="selectedOperationType === 'assignRoles'">
            <el-form-item :label="$t('BulkOperation.Roles')" required>
              <el-select
                v-model="operationConfig.roleIds"
                :placeholder="$t('BulkOperation.SelectRoles')"
                multiple
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="role in roles"
                  :key="role.id"
                  :label="role.displayName"
                  :value="role.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('BulkOperation.AssignMode')">
              <el-radio-group v-model="operationConfig.assignMode">
                <el-radio value="add">{{ $t('BulkOperation.AddRoles') }}</el-radio>
                <el-radio value="replace">{{ $t('BulkOperation.ReplaceRoles') }}</el-radio>
                <el-radio value="remove">{{ $t('BulkOperation.RemoveRoles') }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </template>

          <!-- 租户迁移操作 -->
          <template v-if="selectedOperationType === 'migrateTenant'">
            <el-form-item :label="$t('BulkOperation.TargetTenant')" required>
              <el-select
                v-model="operationConfig.targetTenantId"
                :placeholder="$t('BulkOperation.SelectTargetTenant')"
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="tenant in tenants"
                  :key="tenant.id"
                  :label="tenant.name"
                  :value="tenant.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('BulkOperation.MigrateData')">
              <el-checkbox-group v-model="operationConfig.migrateDataTypes">
                <el-checkbox value="profile">{{ $t('BulkOperation.UserProfile') }}</el-checkbox>
                <el-checkbox value="permissions">{{ $t('BulkOperation.UserPermissions') }}</el-checkbox>
                <el-checkbox value="files">{{ $t('BulkOperation.UserFiles') }}</el-checkbox>
                <el-checkbox value="settings">{{ $t('BulkOperation.UserSettings') }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </template>

          <!-- 密码重置操作 -->
          <template v-if="selectedOperationType === 'resetPassword'">
            <el-form-item :label="$t('BulkOperation.NewPassword')" required>
              <el-input
                v-model="operationConfig.newPassword"
                type="password"
                show-password
                :placeholder="$t('BulkOperation.NewPasswordPlaceholder')"
              />
            </el-form-item>
            <el-form-item :label="$t('BulkOperation.ConfirmPassword')" required>
              <el-input
                v-model="operationConfig.confirmPassword"
                type="password"
                show-password
                :placeholder="$t('BulkOperation.ConfirmPasswordPlaceholder')"
              />
            </el-form-item>
            <el-form-item :label="$t('BulkOperation.RequirePasswordChange')">
              <el-switch
                v-model="operationConfig.requirePasswordChange"
                :active-text="$t('Common.Yes')"
                :inactive-text="$t('Common.No')"
              />
            </el-form-item>
            <el-form-item :label="$t('BulkOperation.NotifyUsers')">
              <el-switch
                v-model="operationConfig.notifyUsers"
                :active-text="$t('Common.Yes')"
                :inactive-text="$t('Common.No')"
              />
            </el-form-item>
          </template>

          <!-- 邮箱验证操作 -->
          <template v-if="selectedOperationType === 'verifyEmail'">
            <el-form-item :label="$t('BulkOperation.SendVerificationEmail')">
              <el-switch
                v-model="operationConfig.sendVerificationEmail"
                :active-text="$t('Common.Yes')"
                :inactive-text="$t('Common.No')"
              />
            </el-form-item>
            <el-form-item :label="$t('BulkOperation.AutoVerify')">
              <el-switch
                v-model="operationConfig.autoVerify"
                :active-text="$t('Common.Yes')"
                :inactive-text="$t('Common.No')"
              />
            </el-form-item>
          </template>
        </el-form>

        <!-- 操作预览 -->
        <div class="operation-preview-list">
          <h4>{{ $t('BulkOperation.AffectedItems') }}</h4>
          <el-table :data="selectedItems.slice(0, 5)" size="small" max-height="200">
            <el-table-column
              prop="name"
              :label="$t('Common.Name')"
              show-overflow-tooltip
            />
            <el-table-column
              prop="email"
              :label="$t('Identity.Email')"
              show-overflow-tooltip
            />
            <el-table-column
              prop="status"
              :label="$t('Common.Status')"
              width="80"
            >
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)" size="small">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
          <div v-if="selectedItems.length > 5" class="more-items">
            {{ $t('BulkOperation.AndMoreItems', { count: selectedItems.length - 5 }) }}
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">
          {{ selectedOperation ? $t('Common.Cancel') : $t('Common.Close') }}
        </el-button>
        <el-button
          v-if="selectedOperation"
          type="primary"
          :loading="loading"
          :disabled="!canExecute"
          @click="handleExecute"
        >
          {{ $t('BulkOperation.Execute') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import {
  ArrowLeft,
  Enable,
  Close,
  Delete,
  User,
  Key,
  Message,
  Switch
} from '@element-plus/icons-vue'
import { userService } from '@/services/user.service'
import { tenantService } from '@/services/tenant.service'
import { authService } from '@/services/AuthService'
import type { BulkOperationRequest } from '@/types/abp'

interface Props {
  modelValue: boolean
  entityType: 'user' | 'tenant'
  selectedItems: any[]
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const formRef = ref<FormInstance>()
const loading = ref(false)
const selectedOperationType = ref('')
const roles = ref<any[]>([])
const tenants = ref<any[]>([])

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 可用操作列表
const availableOperations = computed(() => {
  const operations = []

  if (props.entityType === 'user') {
    operations.push(
      {
        type: 'activate',
        name: $t('BulkOperation.ActivateUsers'),
        description: $t('BulkOperation.ActivateUsersDescription'),
        icon: Enable,
        requiresConfirmation: false
      },
      {
        type: 'deactivate',
        name: $t('BulkOperation.DeactivateUsers'),
        description: $t('BulkOperation.DeactivateUsersDescription'),
        icon: Close,
        requiresConfirmation: true,
        warning: $t('BulkOperation.DeactivateUsersWarning')
      },
      {
        type: 'delete',
        name: $t('BulkOperation.DeleteUsers'),
        description: $t('BulkOperation.DeleteUsersDescription'),
        icon: Delete,
        requiresConfirmation: true,
        warning: $t('BulkOperation.DeleteUsersWarning')
      },
      {
        type: 'assignRoles',
        name: $t('BulkOperation.AssignRoles'),
        description: $t('BulkOperation.AssignRolesDescription'),
        icon: User,
        requiresConfirmation: false
      },
      {
        type: 'resetPassword',
        name: $t('BulkOperation.ResetPasswords'),
        description: $t('BulkOperation.ResetPasswordsDescription'),
        icon: Key,
        requiresConfirmation: true,
        warning: $t('BulkOperation.ResetPasswordsWarning')
      },
      {
        type: 'verifyEmail',
        name: $t('BulkOperation.VerifyEmails'),
        description: $t('BulkOperation.VerifyEmailsDescription'),
        icon: Message,
        requiresConfirmation: false
      }
    )
  } else if (props.entityType === 'tenant') {
    operations.push(
      {
        type: 'activate',
        name: $t('BulkOperation.ActivateTenants'),
        description: $t('BulkOperation.ActivateTenantsDescription'),
        icon: Enable,
        requiresConfirmation: false
      },
      {
        type: 'deactivate',
        name: $t('BulkOperation.DeactivateTenants'),
        description: $t('BulkOperation.DeactivateTenantsDescription'),
        icon: Close,
        requiresConfirmation: true,
        warning: $t('BulkOperation.DeactivateTenantsWarning')
      },
      {
        type: 'delete',
        name: $t('BulkOperation.DeleteTenants'),
        description: $t('BulkOperation.DeleteTenantsDescription'),
        icon: Delete,
        requiresConfirmation: true,
        warning: $t('BulkOperation.DeleteTenantsWarning')
      }
    )
  }

  return operations
})

// 选中的操作
const selectedOperation = computed(() =>
  availableOperations.value.find(op => op.type === selectedOperationType.value)
)

const dialogTitle = computed(() =>
  selectedOperation.value
    ? selectedOperation.value.name
    : $t('BulkOperation.BulkOperation')
)

// 操作配置
const operationConfig = reactive({
  effectiveDate: null,
  reason: '',
  confirmDelete: false,
  deleteReason: '',
  forceDelete: false,
  roleIds: [],
  assignMode: 'add',
  targetTenantId: '',
  migrateDataTypes: [],
  newPassword: '',
  confirmPassword: '',
  requirePasswordChange: true,
  notifyUsers: true,
  sendVerificationEmail: true,
  autoVerify: false
})

// 表单验证规则
const formRules = computed<FormRules>(() => {
  const rules: FormRules = {}

  if (selectedOperationType.value === 'delete') {
    rules.confirmDelete = [
      {
        validator: (rule, value, callback) => {
          if (!value) {
            callback(new Error($t('BulkOperation.ConfirmDeleteRequired')))
          } else {
            callback()
          }
        },
        trigger: 'change'
      }
    ]
    rules.deleteReason = [
      { required: true, message: $t('BulkOperation.DeleteReasonRequired'), trigger: 'blur' }
    ]
  }

  if (selectedOperationType.value === 'assignRoles') {
    rules.roleIds = [
      { required: true, message: $t('BulkOperation.RolesRequired'), trigger: 'change' }
    ]
  }

  if (selectedOperationType.value === 'migrateTenant') {
    rules.targetTenantId = [
      { required: true, message: $t('BulkOperation.TargetTenantRequired'), trigger: 'change' }
    ]
  }

  if (selectedOperationType.value === 'resetPassword') {
    rules.newPassword = [
      { required: true, message: $t('BulkOperation.NewPasswordRequired'), trigger: 'blur' },
      { min: 8, message: $t('BulkOperation.PasswordLength'), trigger: 'blur' }
    ]
    rules.confirmPassword = [
      { required: true, message: $t('BulkOperation.ConfirmPasswordRequired'), trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value !== operationConfig.newPassword) {
            callback(new Error($t('BulkOperation.PasswordMismatch')))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ]
  }

  return rules
})

// 是否可以执行操作
const canExecute = computed(() => {
  if (!selectedOperation.value) return false

  if (selectedOperationType.value === 'delete') {
    return operationConfig.confirmDelete && operationConfig.deleteReason
  }

  if (selectedOperationType.value === 'assignRoles') {
    return operationConfig.roleIds.length > 0
  }

  if (selectedOperationType.value === 'migrateTenant') {
    return operationConfig.targetTenantId && operationConfig.migrateDataTypes.length > 0
  }

  if (selectedOperationType.value === 'resetPassword') {
    return operationConfig.newPassword && operationConfig.confirmPassword &&
           operationConfig.newPassword === operationConfig.confirmPassword
  }

  return true
})

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    active: 'success',
    inactive: 'warning',
    deleted: 'danger',
    pending: 'info'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    active: $t('Common.Active'),
    inactive: $t('Common.Inactive'),
    deleted: $t('Common.Deleted'),
    pending: $t('Common.Pending')
  }
  return statusMap[status] || status
}

// 初始化数据
const initializeData = async () => {
  try {
    if (props.entityType === 'user') {
      // 加载角色列表
      const roleResult = await userService.getRoleList()
      roles.value = roleResult.items
    } else if (props.entityType === 'tenant') {
      // 加载租户列表
      const tenantResult = await tenantService.getTenantList({ maxResultCount: 1000 })
      tenants.value = tenantResult.items
    }
  } catch (error) {
    console.error('初始化批量操作数据失败:', error)
  }
}

// 返回操作选择
const backToSelection = () => {
  selectedOperationType.value = ''
  resetOperationConfig()
}

// 重置操作配置
const resetOperationConfig = () => {
  Object.assign(operationConfig, {
    effectiveDate: null,
    reason: '',
    confirmDelete: false,
    deleteReason: '',
    forceDelete: false,
    roleIds: [],
    assignMode: 'add',
    targetTenantId: '',
    migrateDataTypes: [],
    newPassword: '',
    confirmPassword: '',
    requirePasswordChange: true,
    notifyUsers: true,
    sendVerificationEmail: true,
    autoVerify: false
  })
}

// 处理执行操作
const handleExecute = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    // 显示确认对话框
    const confirmMessage = getConfirmMessage()
    await ElMessageBox.confirm(
      confirmMessage,
      $t('BulkOperation.ConfirmOperation'),
      {
        confirmButtonText: $t('Common.Confirm'),
        cancelButtonText: $t('Common.Cancel'),
        type: 'warning',
        dangerouslyUseHTMLString: true
      }
    )

    loading.value = true

    const operationRequest: BulkOperationRequest = {
      operation: selectedOperationType.value,
      itemIds: props.selectedItems.map(item => item.id),
      parameters: getOperationParameters()
    }

    if (props.entityType === 'user') {
      await userService.bulkOperation(operationRequest)
    } else if (props.entityType === 'tenant') {
      await tenantService.bulkOperation(operationRequest)
    }

    ElMessage.success($t('BulkOperation.OperationSuccess'))
    emit('success')
    handleClose()
  } catch (error: any) {
    console.error('批量操作失败:', error)

    if (error !== 'cancel') {
      if (error.response?.data?.error?.message) {
        ElMessage.error(error.response.data.error.message)
      } else {
        ElMessage.error($t('BulkOperation.OperationFailed'))
      }
    }
  } finally {
    loading.value = false
  }
}

// 获取确认消息
const getConfirmMessage = () => {
  const operation = selectedOperation.value!
  const itemCount = props.selectedItems.length

  let message = `<div><strong>${operation.name}</strong></div>`
  message += `<div>${$t('BulkOperation.ConfirmItemsCount', { count: itemCount })}</div>`

  if (operation.requiresConfirmation && operation.warning) {
    message += `<div style="color: #f56c6c; margin-top: 10px;">${operation.warning}</div>`
  }

  if (selectedOperationType.value === 'delete' && operationConfig.forceDelete) {
    message += `<div style="color: #f56c6c; margin-top: 10px;">${$t('BulkOperation.ForceDeleteConfirm')}</div>`
  }

  return message
}

// 获取操作参数
const getOperationParameters = () => {
  const params: any = {}

  switch (selectedOperationType.value) {
    case 'activate':
    case 'deactivate':
      params.effectiveDate = operationConfig.effectiveDate
      params.reason = operationConfig.reason
      break
    case 'delete':
      params.reason = operationConfig.deleteReason
      params.forceDelete = operationConfig.forceDelete
      break
    case 'assignRoles':
      params.roleIds = operationConfig.roleIds
      params.assignMode = operationConfig.assignMode
      break
    case 'migrateTenant':
      params.targetTenantId = operationConfig.targetTenantId
      params.migrateDataTypes = operationConfig.migrateDataTypes
      break
    case 'resetPassword':
      params.newPassword = operationConfig.newPassword
      params.requirePasswordChange = operationConfig.requirePasswordChange
      params.notifyUsers = operationConfig.notifyUsers
      break
    case 'verifyEmail':
      params.sendVerificationEmail = operationConfig.sendVerificationEmail
      params.autoVerify = operationConfig.autoVerify
      break
  }

  return params
}

// 处理关闭
const handleClose = () => {
  if (loading.value) return

  dialogVisible.value = false
  setTimeout(() => {
    selectedOperationType.value = ''
    resetOperationConfig()
    formRef.value?.resetFields()
  }, 300)
}

// 监听对话框打开
watch(() => props.modelValue, (newValue) => {
  if (newValue) {
    initializeData()
  }
})
</script>

<style scoped>
.bulk-operation-dialog {
  min-height: 400px;
}

.operation-selection h3 {
  margin-bottom: 20px;
  color: #303133;
}

.operation-types {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.operation-radio {
  width: 100%;
  margin-right: 0;
}

.operation-radio :deep(.el-radio__input) {
  margin-top: 20px;
}

.operation-item {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  padding: 16px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.operation-item:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.operation-icon {
  flex-shrink: 0;
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 50%;
  color: #909399;
}

.operation-info {
  flex: 1;
}

.operation-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.operation-description {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.operation-warning {
  margin-top: 8px;
}

.selected-operation-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.selected-operation-header h3 {
  margin: 0;
  color: #303133;
}

.operation-preview {
  margin-bottom: 20px;
}

.operation-form {
  margin-bottom: 20px;
}

.form-help {
  margin-top: 5px;
  font-size: 12px;
}

.operation-preview-list h4 {
  margin-bottom: 10px;
  color: #303133;
}

.more-items {
  text-align: center;
  padding: 10px;
  color: #909399;
  font-size: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-top: 10px;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-checkbox-group) {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

:deep(.el-radio-group) {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
</style>